package com.bottle.client;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

/**
 * @author: chenyuncong
 * @Date: 2019/12/3 10:59
 */
@Slf4j
public class PollingClient {

    @Autowired
    private CharClient charClient;

    @Value("${bottle.server.url}")
    private String url;

    ScheduledExecutorService executor = null;
    LinkedBlockingQueue<String> linkedBlockingQueue = null;
    ExecutorService singleThreadExecutor = null;
    private boolean sign = false;

    public PollingClient() {
    }

    @PostConstruct
    public void init() {
        sign = true;
        linkedBlockingQueue = new LinkedBlockingQueue<>();
        executor = Executors.newScheduledThreadPool(1);
        singleThreadExecutor = Executors.newSingleThreadExecutor(); //单个
        executor.scheduleWithFixedDelay(new PollingRunnable(), 5000, 10, TimeUnit.MILLISECONDS);
        singleThreadExecutor.execute(new WorkRunnable());
        log.info("启动polLong");
    }

    @PreDestroy
    public void destroy() throws InterruptedException {
        if (sign) {
            log.info("开始销毁polLong对象");
            sign = false;
            linkedBlockingQueue.put("");
            executor.shutdown();
            singleThreadExecutor.shutdown();
        }
    }

    public String getPolling(String val) {
        return "polling:" + val;
    }

    //返回数据
    class WorkRunnable implements Runnable {
        public WorkRunnable(){
        }
        @Override
        public void run() {
            try {
                while (sign) {
                    String json = linkedBlockingQueue.take();
                    if(StringUtils.isEmpty(json)){
                        return;
                    }
                    charClient.receive(json);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    //轮询接口
    class PollingRunnable implements Runnable {
        public PollingRunnable() {}
        @Override
        public void run() {
            try {
//                String url ="";
                String uuid = UUID.randomUUID().toString();
                Long startTime = System.currentTimeMillis();
//                log.info("启动请求:[{}],[{}]",uuid,startTime);
                Map<String, String> map = new HashMap<>();
//                map.put("name", "0");
                String json = OkHttpRequestUtils.doPost(url+"watch/cad71708824dca82",map);
//                OkHttpRequestUtils.doPost("http://localhost:8081/watch/b003e8895fc08316", map);
//                log.info("json:[{}]",json);
                JSONObject jsonObject = JSONObject.parseObject(json);
                Integer code = jsonObject.getInteger("code");
                if (code == 200) {
                    linkedBlockingQueue.put(jsonObject.getString("data"));
                } else {
                    log.info("code:{}获取超时，继续获取", code);
                }
//                log.info("请求结束：[{}],[{}]",uuid,(System.currentTimeMillis()-startTime));
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    Thread.sleep(1000);//防止死循环
                } catch (InterruptedException e1) {
                }
            }
        }
    }

}


